package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/menu")
public class MenuController {

    //远程注入
    @Reference
    private MenuService menuService;
    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {

        PageResult pageResult = menuService.pageQuery(queryPageBean);
        return pageResult;
    }


    //按ID查询
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try{
            Menu menu=menuService.findById(id);
            return new Result(true, MessageConstant.QUERY_MENU_SUCCESS,menu);
        }catch(Exception e){
            e.printStackTrace();
            //如果失败 则返回失败
            return new Result(false, MessageConstant.QUERY_MENU_FAIL);
        }
    }
    @RequestMapping("/findParentId")
    public Result findParentId(){
        try{
           List<Map<String,Integer>> options=menuService.findParentId();
            return new Result(true, MessageConstant.QUERY_MENU_SUCCESS,options);
        }catch(Exception e){
            e.printStackTrace();
            //如果失败 则返回失败
            return new Result(false, MessageConstant.QUERY_MENU_FAIL);
        }
    }

    //新增权限
    @RequestMapping("/add")
    public Result add(@RequestBody Menu menu){
        try{
            menuService.add(menu);
        }catch(Exception e){
            e.printStackTrace();
            //如果失败 则返回失败
            return new Result(false, MessageConstant.ADD_MENU_FAIL);
        }
        return new Result(true, MessageConstant.ADD_MENU_SUCCESS);
    }

    //删除
    @RequestMapping("/delete")
    public Result delete(Integer id){
        try {
            menuService.delete(id);
            return new Result(true,MessageConstant.DELETE_MENU_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_MENU_FAIL);
        }
    }

    //修改
    @RequestMapping("/edit")
    public Result edit(@RequestBody Menu menu){
        try{
            menuService.edit(menu);

            return new Result(true, MessageConstant.EDIT_MENU_SUCCESS);
        }catch(Exception e){
            e.printStackTrace();
            //如果失败 则返回失败
            return new Result(false, MessageConstant.EDIT_MENU_FAIL);
        }
    }

}
